package com.victor.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.victor.entity.LookThings;
import com.victor.service.DemoService;
import com.victor.service.LookThingsService;
import com.victor.utils.FileUpload;
import com.victor.utils.Msg;
import com.victor.utils.photo_compare.ImgSimilarity;

@RestController
public class DemoController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private LookThingsService lookThingsService;
	@Autowired
	private DemoService demoService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpSession session;

	// 上传图片解析灰度存入数据库
	@RequestMapping("/submitPhoto")
	public Msg upload(MultipartFile file) throws IOException {
		String uploadFile = null;
		try {
			uploadFile = FileUpload.uploadFile(file, request, "file");
		} catch (Exception e) {
			logger.error("--FileController.errorInfo>:{}", e);
			return Msg.fail();
		}

		String filePath = session.getServletContext().getRealPath("/");
		int[] intfile = ImgSimilarity.getImgFinger(new File(filePath + uploadFile));

		LookThings lookthings = new LookThings();
		lookthings.setIntroduction("图片介绍");
		lookthings.setPhoto(uploadFile);

		String s1 = ""; // 定义一个空字符串
		StringBuffer sb = new StringBuffer(s1); // 创建字符串缓冲区对象sb，将s1对象传进去（如果不用缓冲区的话，没加一个数组元素，及重新生成一个String对象）
		for (int i = 0; i < intfile.length; i++) {
			if (i == intfile.length) {
				sb.append(intfile[i]); // 遍历int数组，追加到sb;
			} else {
				sb.append(intfile[i] + ","); // 遍历int数组，追加到sb;
			}
		}
		String s2 = sb.toString(); // 返回缓冲区对象的toString(),即得到的字符串

		lookthings.setPixels(s2);
		demoService.addlookthings(lookthings);
		return Msg.success().add("path", uploadFile);
	}

	// 对比
	@PostMapping("/duibi")
	public Msg duibi(MultipartFile duibifile) throws IOException {
		String uploadFile = null;
		try {
			uploadFile = FileUpload.uploadFile(duibifile, request, "file");
		} catch (Exception e) {
			return Msg.fail();
		}

		List<LookThings> list = lookThingsService.getAll();
		HashMap<String, LookThings> map = new HashMap<String, LookThings>();
		Double temp = 0.0;

		String filePath = session.getServletContext().getRealPath("/");
		File file = new File(filePath + uploadFile);
		int[] fileint = ImgSimilarity.getImgFinger(file);
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {

				try {

					double similarity = ImgSimilarity.getSimilarity(fileint, stringConvertInt(list.get(i).getPixels()));
					if (temp < similarity) {
						temp = similarity;
						map.put("path", list.get(i));
					}

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Msg.success().add(String.valueOf(temp), "http://localhost:8888/" + map.get("path").getPhoto());

	}

	private int[] stringConvertInt(String value) {
		int[] intArr = new int[0];

		String[] valueArr = value.split(",");
		intArr = new int[valueArr.length];
		for (int i = 0; i < valueArr.length; i++) {
			intArr[i] = Integer.parseInt(valueArr[i]);
		}

		return intArr;
	}

}
